// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// P [author] rhyme_lph
// d [email]  rhymelph@gmail.com
// v [github] https://github.com/rhymelph

import 'dart:async';

import 'package:base_plugin/base_plugin.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:r_barcode/r_barcode.dart';

class BarCodeCameraProvider extends BaseProvider {
  RBarcodeCameraController controller;
  RBarcodeResult result;

  @override
  void initState() {
    super.initState();
    RBarcode.initBarcodeEngine(isDebug: true, isReturnImage: false)
        .then((value) {
      RBarcode.availableBarcodeCameras().then((value) {
        print('摄像头：${value.toString()}');
        try {
          controller = RBarcodeCameraController(
              value[0], RBarcodeCameraResolutionPreset.max,
              formats: RBarcodeFormat.kLineFormats, isDebug: false)
            ..addListener(_handleResultListener)
            ..initialize().then(_handleInitListener);
        } catch (e) {
          print(e);
        }
      });
    });
  }

  //处理结果返回
  void _handleResultListener() {
    if (controller?.result != result) {
      HapticFeedback.vibrate();
      _handleScanStop();
      obtainContext?.call((context) {
        Navigator.of(context).pop(controller.result.text);
      });
    }
  }

  void _handleScanStop() {
    controller?.stopScan();
  }

  FutureOr _handleInitListener(void value) {
    if (controller?.value?.isInitialized == true) {
      update();
    }
  }

  @override
  Future get dataFuture => null;
}
